package com.tars.txtm.netty;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tars.txtm.enums.TxEnum;
import com.tars.txtm.trasactional.MyTransactional;
import com.tars.txtm.trasactional.MyTransactionalManager;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import static com.tars.txtm.enums.TxEnum.commit;
import static com.tars.txtm.enums.TxEnum.rollback;

/**
 * @author: Franz 2022/3/19
 */
public class NettyClientHandler extends SimpleChannelInboundHandler<String> {

    private ChannelHandlerContext context;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        context = ctx;
    }

    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        //1.获取全局事务整体响应结果
        System.out.println("接收数据："+ msg);
        JSONObject jsonObject = JSONObject.parseObject(msg);
        String groupId = jsonObject.getString("groupId");
        Integer status = Integer.valueOf(jsonObject.getString("status"));

        //2.更新事务状态
        MyTransactional tx = MyTransactionalManager.getCurrentThreadTX(groupId);
        TxEnum type = TxEnum.getType(status);
        switch (type){
            case rollback:
                tx.setStatus(rollback);
                break;
            case commit:
                tx.setStatus(commit);
                break;
            default:
                tx.setStatus(rollback);
                break;
        }

        //3.通知本地执行事务
        tx.getTask().singalTask();
    }

    public void call(JSONObject msg){
        context.writeAndFlush(msg.toJSONString());
    }
}
